package com.draven.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.draven.common.Result;
import com.draven.entity.Sticky;
import com.draven.service.StickyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 便签控制器
 */
@RestController
@RequestMapping("/sticky")
public class StickyController {

    @Autowired
    private StickyService stickyService;

    /**
     * 添加便签
     */
    @PostMapping("/add")
    public Result<Long> add(
            HttpServletRequest request,
            @RequestBody Sticky sticky) {
        Long userId = (Long) request.getAttribute("userId");
        sticky.setUserId(userId);
        Long id = stickyService.add(sticky);
        return Result.success(id);
    }

    /**
     * 修改便签
     */
    @PostMapping("/update")
    public Result<Void> update(
            HttpServletRequest request,
            @RequestBody Sticky sticky) {
        Long userId = (Long) request.getAttribute("userId");
        sticky.setUserId(userId);
        stickyService.update(sticky);
        return Result.success();
    }

    /**
     * 删除便签
     */
    @PostMapping("/delete")
    public Result<Void> delete(
            HttpServletRequest request,
            @NotNull(message = "ID不能为空") @RequestParam Long id) {
        Long userId = (Long) request.getAttribute("userId");
        stickyService.delete(id, userId);
        return Result.success();
    }

    /**
     * 获取便签详情
     */
    @GetMapping("/detail")
    public Result<Sticky> detail(
            HttpServletRequest request,
            @NotNull(message = "ID不能为空") @RequestParam Long id) {
        Long userId = (Long) request.getAttribute("userId");
        Sticky detail = stickyService.getDetail(id, userId);
        return Result.success(detail);
    }

    /**
     * 获取用户的所有便签
     */
    @GetMapping("/list")
    public Result<List<Sticky>> list(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        List<Sticky> list = stickyService.listByUserId(userId);
        return Result.success(list);
    }

    /**
     * 分页查询便签
     */
    @GetMapping("/page")
    public Result<Page<Sticky>> page(
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Long userId = (Long) request.getAttribute("userId");
        Page<Sticky> page = stickyService.page(userId, pageNum, pageSize);
        return Result.success(page);
    }
} 